﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using coffeeshop.Models;

namespace coffeeshop.Forms
{
    public partial class frmEditUser : Form
    {
        private User theUser { get; set; }

        public Form MyParentForm { get; set; }

        public frmEditUser(User _user)
        {
            InitializeComponent();

            LoadUserRoles();

            if (_user != null)
            {
                theUser = _user;
                LoadUserInfo();
            }
        }

        private void LoadUserInfo()
        {
            if (theUser != null)
            {
                theUser = User.GetById(theUser.UserId);
                txtName.Text = theUser.Name;
                txtPassword.Text = theUser.Password;
                txtTitle.Text = theUser.Title;
                cboRole.SelectedValue = theUser.UserRoleId;
            }
        }

        private void LoadUserRoles()
        {
            var _list = new[] { 
                new { Name = Global.GetRoleName(Global.UserRoleId.Admin), UserRoleId = (int)Global.UserRoleId.Admin }, 
                new { Name = Global.GetRoleName(Global.UserRoleId.Cashier), UserRoleId = (int)Global.UserRoleId.Cashier },
                new { Name = Global.GetRoleName(Global.UserRoleId.Waiter), UserRoleId = (int)Global.UserRoleId.Waiter }};

            cboRole.DataSource = _list;
            cboRole.DisplayMember = "Name";
            cboRole.ValueMember = "UserRoleId";
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            // verify the user input
            bool hasEmptyTextBox = Controls.OfType<TextBox>()
                               .Any(tb => String.IsNullOrWhiteSpace(tb.Text));

            if (hasEmptyTextBox)
            {
                MessageBox.Show("Bạn cần điển đầy đủ thông tin");
                return;
            }

            if (theUser == null)
            {
                theUser = new User();
            }

            theUser.Name = txtName.Text.Trim();
            theUser.Password = txtPassword.Text.Trim();
            theUser.Title = txtTitle.Text.Trim();
            theUser.UserRoleId = (int)cboRole.SelectedValue;

            if (theUser.Save())
            {
                // Reload the list
                frmUserList userList = (frmUserList)MyParentForm;
                userList.ReloadList();
                this.Close();  
            }
            else
            {
                MessageBox.Show("Có lỗi trong quá trình lưu");
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
